package edu.chen.service.impl;

import edu.chen.dao.BookDao;
import edu.chen.dao.LeaseDao;
import edu.chen.entity.Book;
import edu.chen.entity.Lease;
import edu.chen.entity.Student;
import edu.chen.exception.lease.NoNumberException;
import edu.chen.exception.lease.NotFountException;
import edu.chen.exception.lease.RepeatLeaseException;
import edu.chen.exception.rebook.NoLeaseException;
import edu.chen.exception.rebook.ReturnException;
import edu.chen.service.LeaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class LeaseServiceImpl implements LeaseService{
    private final LeaseDao leaseDao;
    private final BookDao bookDao;

    @Autowired
    public LeaseServiceImpl(LeaseDao leaseDao, BookDao bookDao) {
        this.leaseDao = leaseDao;
        this.bookDao = bookDao;
    }

    @Transactional
    public Lease leaseBook(int book_id, int student_id) throws NotFountException,NoNumberException,RepeatLeaseException{
        //取出相应的书本信息 便于判断库存是否足够
        Book book = bookDao.queryById(book_id);
        if (book == null) {   //排除书本不存在的错误
            throw new NotFountException("not fount this book");   //抛出错误,已便于上层捕获
        }
        if (book.getBook_number() < 1) {  //排除书本库存不足错误
            throw new NoNumberException("no number");
        }
        if(leaseDao.query(book_id,student_id) != null){     //排除多次租借错误
            throw new RepeatLeaseException("repeat lease");
        }else {
            book.setBook_number(book.getBook_number() - 1);
            bookDao.update(book);
            Lease lease = new Lease(new Book(book_id,null), new Student(student_id,null));    //创建租借条目对象
            leaseDao.add(lease);                            //添加租借条目
            return lease;
        }
    }

    @Transactional
    public void returnBook(int book_id, int student_id) {
        try {
            Lease lease = leaseDao.query(book_id, student_id);
            if (lease == null) {       //排除记录不存在错误
                throw new NoLeaseException("没有租借记录");
            }

            Book book = bookDao.queryById(book_id);
            book.setBook_number(book.getBook_number() + 1);
            bookDao.update(book);                   //增加书本数目

            leaseDao.delete(book_id, student_id);
        }catch (ReturnException e){
            throw new ReturnException("归还书本失败");
        }
    }

    @Transactional
    public List<Lease> getLeaseByStudentId(int student_id){
        return leaseDao.queryByStudentId(student_id);
    }
}
